package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.his.po.Diagnosis; // 需创建诊断实体类
import com.neuedu.his.service.DiagnosisService; // 需创建诊断服务接口
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 诊断管理控制器
 * 处理诊断的保存、确认等操作
 */
@RestController
@RequestMapping("/api/diagnosis")
public class DiagnosisController {

    private static final Logger log = LoggerFactory.getLogger(DiagnosisController.class);

    @Autowired
    private DiagnosisService diagnosisService;

    /**
     * 获取患者诊断信息
     * 前端调用：/api/diagnosis?caseNumber=xxx
     */
    @GetMapping
    public ResponseEntity<Diagnosis> getDiagnosisInfo(@RequestParam String caseNumber) {
        try {
            if (caseNumber == null || caseNumber.isEmpty()) {
                log.warn("获取诊断信息失败：病历号为空");
                return ResponseEntity.badRequest().build();
            }

            QueryWrapper<Diagnosis> wrapper = new QueryWrapper<>();
            wrapper.eq("case_number", caseNumber); // 假设数据库字段为case_number
            Diagnosis diagnosis = diagnosisService.getOne(wrapper);

            if (diagnosis == null) {
                log.info("未找到诊断记录，病历号：{}", caseNumber);
                Diagnosis emptyDiagnosis = new Diagnosis();
                emptyDiagnosis.setCaseNumber(caseNumber); // 初始化病历号
                return ResponseEntity.ok(emptyDiagnosis);
            }

            log.info("获取诊断信息成功，病历号：{}", caseNumber);
            return ResponseEntity.ok(diagnosis);
        } catch (Exception e) {
            log.error("获取诊断信息异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 保存诊断（暂存）
     * 前端调用：/api/diagnosis/save
     */
    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> saveDiagnosis(@RequestBody Diagnosis diagnosis) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (diagnosis == null || diagnosis.getCaseNumber() == null) {
                log.warn("保存诊断失败：参数无效");
                result.put("success", false);
                result.put("message", "参数无效");
                return ResponseEntity.badRequest().body(result);
            }

            // 暂存时标记为未确认
            diagnosis.setConfirmed(false);
            diagnosisService.saveOrUpdate(diagnosis);

            result.put("success", true);
            result.put("data", diagnosis);
            log.info("暂存诊断成功，病历号：{}", diagnosis.getCaseNumber());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("保存诊断异常", e);
            result.put("success", false);
            result.put("message", "服务器错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 确认诊断（提交）
     * 前端调用：/api/diagnosis/confirm（解决404的核心接口）
     */
    @PostMapping("/confirm")
    public ResponseEntity<Map<String, Object>> confirmDiagnosis(@RequestBody Diagnosis diagnosis) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (diagnosis == null || diagnosis.getCaseNumber() == null) {
                log.warn("确认诊断失败：参数无效");
                result.put("success", false);
                result.put("message", "参数无效");
                return ResponseEntity.badRequest().body(result);
            }

            // 校验主要诊断是否为空
            if (diagnosis.getMainDiagnosis() == null || diagnosis.getMainDiagnosis().isEmpty()) {
                result.put("success", false);
                result.put("message", "主要诊断不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 确认诊断时更新状态和时间
            diagnosis.setConfirmed(true);
            diagnosis.setConfirmedTime(LocalDateTime.now()); // 记录确认时间
            diagnosisService.saveOrUpdate(diagnosis);

            result.put("success", true);
            result.put("data", diagnosis);
            log.info("确认诊断成功，病历号：{}", diagnosis.getCaseNumber());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("确认诊断异常", e);
            result.put("success", false);
            result.put("message", "服务器错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}